<template>
  <div class="domain-management">
    <!-- 获取域名和添加域名按钮 -->
    <div class="operation-row">
      <el-button
        type="primary"
        @click="showGetDomainDialog"
        >获取域名数量</el-button
      >
      <el-button
        type="primary"
        @click="showAddDomainDialog"
        >添加域名</el-button
      >
    </div>

    <!-- 统计信息和搜索 -->
    <div class="search-row">
      <div class="stat-item">可获取域名数：{{ availableDomains }}</div>
      <div class="stat-item">检测时间：{{ checkTime ? checkTime : "-" }}</div>
      <div class="search-input">
        <el-input
          v-model="searchDomain"
          placeholder="请输入域名名称" />
      </div>
      <el-button
        type="primary"
        @click="handleSearch"
        >搜索</el-button
      >
    </div>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%">
      <el-table-column
        prop="id"
        label="ID"
        width="80" />
      <el-table-column
        prop="domainName"
        label="域名名称" />
      <el-table-column
        prop="storeCount"
        label="使用门店数"
        width="120" />
      <el-table-column
        label="域名状态"
        width="120">
        <template #default="{ row }">
          {{ row.status === 1 ? "疑似封控" : "正常" }}
        </template>
      </el-table-column>
      <el-table-column
        label="自动分配门店"
        width="120">
        <template #default="{ row }">
          {{ row.autoAssign === 0 ? "否" : "是" }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="600">
        <template #default="{ row }">
          <el-button
            type="primary"
            link
            @click="showBatchUpdateDialog(row)"
            >批量更新域名</el-button
          >
          <el-button
            type="primary"
            link
            @click="showStoreListDialog(row)"
            >门店列表</el-button
          >
          <el-button
            v-if="row.status3 === 0"
            type="primary"
            link
            @click="showBindStoreDialog(row)"
            >绑定门店</el-button
          >
          <el-button
            v-if="row.status3 === 0"
            type="primary"
            link
            @click="handleDeleteStore(row)"
            >删除门店</el-button
          >
          <el-button
            v-if="row.status3 === 1"
            type="primary"
            link
            @click="handleAuthorizeDomain(row)"
            >授权域名</el-button
          >
          <el-button
            v-if="row.status3 === 2"
            type="primary"
            link
            disabled
            >授权域名(使用中)</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 获取域名数量对话框 -->
    <el-dialog
      v-model="getDomainDialogVisible"
      title="获取域名数量"
      width="500px"
      :destroy-on-close="true">
      <el-form
        :model="getDomainForm"
        :rules="getDomainRules"
        ref="getDomainFormRef">
        <el-form-item
          label="获取数量"
          prop="domain"
          :label-width="'80px'">
          <el-input v-model="getDomainForm.domain" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="getDomainDialogVisible = false"
            >取消编辑</el-button
          >
          <el-button
            type="primary"
            @click="handleGetDomain"
            >保存数据</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 添加域名对话框 -->
    <el-dialog
      v-model="addDomainDialogVisible"
      title="添加"
      width="500px"
      :destroy-on-close="true">
      <el-form
        :model="addDomainForm"
        :rules="addDomainRules"
        ref="addDomainFormRef">
        <el-form-item
          label="域名名称"
          prop="domainName"
          :label-width="'80px'">
          <el-input v-model="addDomainForm.domainName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDomainDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleAddDomain"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 批量更新域名对话框 -->
    <el-dialog
      v-model="batchUpdateDialogVisible"
      title="更新域名"
      width="500px"
      :destroy-on-close="true">
      <el-form
        :model="batchUpdateForm"
        :rules="batchUpdateRules"
        ref="batchUpdateFormRef">
        <el-form-item
          label="更新的域名id"
          prop="domainId"
          :label-width="'120px'">
          <el-input v-model="batchUpdateForm.domainId" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchUpdateDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleBatchUpdate"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 门店列表对话框 -->
    <el-dialog
      v-model="storeListDialogVisible"
      title="门店列表"
      width="800px"
      :destroy-on-close="true">
      <el-table
        :data="storeList"
        border>
        <el-table-column
          prop="id"
          label="ID"
          width="80" />
        <el-table-column
          prop="storeId"
          label="门店id"
          width="120" />
        <el-table-column
          prop="storeName"
          label="门店名称" />
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="storeListCurrentPage"
          v-model:page-size="storeListPageSize"
          :total="storeListTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleStoreListSizeChange"
          @current-change="handleStoreListCurrentChange" />
      </div>
    </el-dialog>

    <!-- 绑定门店对话框 -->
    <el-dialog
      v-model="bindStoreDialogVisible"
      title="绑定门店"
      width="500px"
      :destroy-on-close="true">
      <el-form
        :model="bindStoreForm"
        :rules="bindStoreRules"
        ref="bindStoreFormRef">
        <el-form-item
          label="绑定门店"
          prop="storeId"
          :label-width="'80px'">
          <el-select
            v-model="bindStoreForm.storeId"
            placeholder="请选择门店">
            <el-option
              v-for="store in storeOptions"
              :key="store.id"
              :label="store.title"
              :value="store.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bindStoreDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleBindStore"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import {
  getHostList,
  hostStore,
  hostAddDomain,
  hostAddHost,
  hostStoreBind,
  hostDelBind,
  hostAuthHost,
  hostUpdateDomain,
  getStoreList,
} from "@/addon/htscrm/api/domainManagement";

/**
 * 接口定义
 */
// 域名列表项接口
interface DomainItem {
  id: number; // 域名ID
  domainName: string; // 域名名称
  storeCount: number; // 使用门店数量
  status: number; // 域名状态：0-疑似封控，1-正常
  autoAssign: number; // 自动分配门店：0-否，1-是
  status3: number; // 域名授权状态：0-未授权，1-已授权，2-使用中
}

// 门店列表项接口
interface StoreItem {
  id: number; // 门店ID
  storeId: string; // 门店编号
  storeName: string; // 门店名称
}

// 门店选项接口（用于下拉选择）
interface StoreOption {
  id: number; // 门店ID
  title: string; // 门店名称
}

/**
 * 数据定义
 */
// 统计信息
const availableDomains = ref(0); // 可获取域名数量
const checkTime = ref(""); // 检测时间

// 搜索相关
const searchDomain = ref(""); // 搜索关键词

// 表格相关
const tableData = ref<DomainItem[]>([]); // 表格数据
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页条数
const total = ref(0); // 总条数

// 门店列表相关
const storeList = ref<StoreItem[]>([]); // 门店列表数据
const storeListCurrentPage = ref(1); // 门店列表当前页码
const storeListPageSize = ref(10); // 门店列表每页条数
const storeListTotal = ref(0); // 门店列表总条数
const storeOptions = ref<StoreOption[]>([]); // 门店选项数据

/**
 * 对话框显示状态
 */
const getDomainDialogVisible = ref(false); // 获取域名对话框
const addDomainDialogVisible = ref(false); // 添加域名对话框
const batchUpdateDialogVisible = ref(false); // 批量更新对话框
const storeListDialogVisible = ref(false); // 门店列表对话框
const bindStoreDialogVisible = ref(false); // 绑定门店对话框

/**
 * 表单数据
 */
const getDomainForm = reactive({
  domain: "", // 域名
});

const addDomainForm = reactive({
  domainName: "", // 域名名称
});

const oldDomainId = ref("");
const batchUpdateForm = reactive({
  domainId: "", // 更新的域名ID
});

const oldHostId = ref("");
const bindStoreForm = reactive({
  storeId: "", // 绑定的门店ID
});

/**
 * 表单校验规则
 */
const getDomainRules = reactive<FormRules>({
  domain: [{ required: true, message: "请输入域名", trigger: "blur" }],
});

const addDomainRules = reactive<FormRules>({
  domainName: [{ required: true, message: "请输入域名名称", trigger: "blur" }],
});

const batchUpdateRules = reactive<FormRules>({
  domainId: [
    { required: true, message: "请输入更新的域名id", trigger: "blur" },
  ],
});

const bindStoreRules = reactive<FormRules>({
  storeId: [{ required: true, message: "请选择门店", trigger: "change" }],
});

/**
 * 表单引用
 */
const getDomainFormRef = ref<FormInstance>();
const addDomainFormRef = ref<FormInstance>();
const batchUpdateFormRef = ref<FormInstance>();
const bindStoreFormRef = ref<FormInstance>();

/**
 * 模拟数据
 */
// 模拟域名列表数据
const mockTableData: DomainItem[] = [
  {
    id: 1,
    domainName: "example1.com",
    storeCount: 5,
    status: 1,
    autoAssign: 1,
    status3: 0,
  },
  {
    id: 2,
    domainName: "example2.com",
    storeCount: 3,
    status: 0,
    autoAssign: 0,
    status3: 1,
  },
  {
    id: 3,
    domainName: "example3.com",
    storeCount: 8,
    status: 1,
    autoAssign: 1,
    status3: 2,
  },
];

// 模拟门店列表数据
const mockStoreList: StoreItem[] = [
  { id: 1, storeId: "S001", storeName: "门店A" },
  { id: 2, storeId: "S002", storeName: "门店B" },
  { id: 3, storeId: "S003", storeName: "门店C" },
];

// 模拟门店选项数据
const mockStoreOptions: StoreOption[] = [
  { id: 1, title: "门店A" },
  { id: 2, title: "门店B" },
  { id: 3, title: "门店C" },
];

/**
 * 模拟接口函数
 */
// 获取域名列表数据
const fetchTableData = async (page: number, size: number, search?: string) => {
  // 模拟API延迟
  await new Promise((resolve) => setTimeout(resolve, 500));

  let filteredData = [...mockTableData];
  if (search) {
    filteredData = filteredData.filter((item) =>
      item.domainName.toLowerCase().includes(search.toLowerCase())
    );
  }

  const start = (page - 1) * size;
  const end = start + size;

  return {
    data: filteredData.slice(start, end),
    total: filteredData.length,
  };
};

// 获取门店列表数据
const fetchStoreList = async (page: number, size: number) => {
  await new Promise((resolve) => setTimeout(resolve, 500));
  const start = (page - 1) * size;
  const end = start + size;

  return {
    data: mockStoreList.slice(start, end),
    total: mockStoreList.length,
  };
};

/**
 * 方法定义
 */
// 显示获取域名对话框
const showGetDomainDialog = () => {
  getDomainDialogVisible.value = true;
};

// 显示添加域名对话框
const showAddDomainDialog = () => {
  addDomainDialogVisible.value = true;
};

// 显示批量更新对话框
const showBatchUpdateDialog = (row: any) => {
  batchUpdateDialogVisible.value = true;
  oldDomainId.value = row.id;
};

const getStoreListData = async () => {
  const result = await hostStore({
    id: oldHostId.value,
    page: storeListCurrentPage.value,
    limit: storeListPageSize.value,
  });
  storeList.value = result.data.data.map((item: any) => {
    return {
      id: item.id,
      storeId: item.store_id,
      storeName: item.title,
    };
  });
  storeListTotal.value = result.data.total;
};

// 显示门店列表对话框
const showStoreListDialog = async (row: any) => {
  storeListDialogVisible.value = true;
  oldHostId.value = row.id;
  getStoreListData();
};

// 显示绑定门店对话框
const showBindStoreDialog = async (row: any) => {
  bindStoreDialogVisible.value = true;
  oldHostId.value = row.id;
  const res = await getStoreList({
    page: 1,
    limit: 120,
  });
  storeOptions.value = res.data.data;
};

// 搜索处理
const handleSearch = async () => {
  try {
    const res = await getHostList({
      page: currentPage.value,
      limit: pageSize.value,
      host: searchDomain.value,
    });
    tableData.value = res.data.data.map((item: any) => {
      return {
        id: item.id,
        domainName: item.host,
        storeCount: item.store_num,
        status: item.wechat_status,
        autoAssign: item.status,
        status3: item.is_auth === 0 ? 0 : item.is_use === 0 ? 1 : 2,
      };
    });
    checkTime.value = res.data.check_time;
    total.value = res.data.total;
    availableDomains.value = res.data.total;
  } catch (e) {
    console.log(e);
  }
};

// 获取域名处理
const handleGetDomain = async () => {
  if (!getDomainFormRef.value) return;
  await getDomainFormRef.value.validate(async (valid) => {
    if (valid) {
      const res = await hostAddDomain({
        num: +getDomainForm.domain,
      });
      if (res.code === 1) {
        ElMessage.success("获取域名数量成功");
        getDomainDialogVisible.value = false;
        handleSearch();
      } else {
        ElMessage.error("获取域名数量失败");
      }
    }
  });
};

// 添加域名处理
const handleAddDomain = async () => {
  if (!addDomainFormRef.value) return;
  await addDomainFormRef.value.validate(async (valid) => {
    if (valid) {
      const res = await hostAddHost({
        host: addDomainForm.domainName,
      });
      if (res.code === 1) {
        ElMessage.success("添加域名成功");
        addDomainDialogVisible.value = false;
        handleSearch();
      } else {
        ElMessage.error("添加域名失败");
      }
    }
  });
};

// 批量更新处理
const handleBatchUpdate = async () => {
  if (!batchUpdateFormRef.value) return;
  await batchUpdateFormRef.value.validate(async (valid) => {
    if (valid) {
      const res = await hostUpdateDomain({
        id: oldDomainId.value,
        new_host_id: batchUpdateForm.domainId,
      });
      if (res.code === 1) {
        ElMessage.success("批量更新成功");
        batchUpdateDialogVisible.value = false;
        handleSearch();
      } else {
        ElMessage.error("批量更新失败");
      }
    }
  });
};

// 绑定门店处理
const handleBindStore = async () => {
  if (!bindStoreFormRef.value) return;
  await bindStoreFormRef.value.validate(async (valid) => {
    if (valid) {
      const res = await hostStoreBind({
        store_id: bindStoreForm.storeId,
        host_id: oldHostId.value,
      });
      if (res.code === 1) {
        ElMessage.success("绑定门店成功");
        bindStoreDialogVisible.value = false;
        handleSearch();
      } else {
        ElMessage.error("绑定门店失败");
      }
    }
  });
};

// 删除门店处理
const handleDeleteStore = async (row: any) => {
  const res = await hostDelBind({
    id: row.id,
  });
  if (res.code === 1) {
    ElMessage.success("删除门店成功");
    handleSearch();
  } else {
    ElMessage.success("删除门店失败");
  }
};

// 授权域名处理
const handleAuthorizeDomain = async (row: any) => {
  const res = await hostAuthHost({
    id: row.id,
  });
  if (res.code === 1) {
    ElMessage.success("授权域名成功");
    handleSearch();
  } else {
    ElMessage.success("授权域名失败");
  }
};

// 表格分页大小改变处理
const handleSizeChange = async (val: number) => {
  pageSize.value = val;
  handleSearch();
};

// 表格页码改变处理
const handleCurrentChange = async (val: number) => {
  currentPage.value = val;
  handleSearch();
};

// 门店列表分页大小改变处理
const handleStoreListSizeChange = async (val: number) => {
  storeListPageSize.value = val;
  getStoreListData();
  // const result = await fetchStoreList(storeListCurrentPage.value, val);
  // storeList.value = result.data;
  // storeListTotal.value = result.total;
};

// 门店列表页码改变处理
const handleStoreListCurrentChange = async (val: number) => {
  storeListCurrentPage.value = val;
  getStoreListData();
  // const result = await fetchStoreList(val, storeListPageSize.value);
  // storeList.value = result.data;
  // storeListTotal.value = result.total;
};

/**
 * 生命周期钩子
 */
// 组件挂载时初始化数据
onMounted(async () => {
  handleSearch();
});
</script>

<style lang="scss" scoped>
.domain-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;

  // 操作按钮行样式
  .operation-row {
    margin-bottom: 20px;
  }

  // 搜索行样式
  .search-row {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 20px;

    .stat-item {
      min-width: 150px;
    }

    .search-input {
      width: 300px;
    }
  }

  // 分页容器样式
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  // 对话框底部按钮样式
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style>
